package com.ibeeking.found.cop.b.rest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ibeeking.found.cop.b.rest.service.IMsgFansMomentTaskFriendsService;
import com.ibeeking.found.cop.b.rest.service.IWxOpenService;
import com.ibeeking.found.cop.service.common.dos.CopEmployeeDO;
import com.ibeeking.found.cop.service.common.dos.MsgFansMomentTaskFriendsDO;
import com.ibeeking.found.cop.service.common.query.MsgFansMomentTaskFriendsQuery;
import com.ibeeking.found.cop.service.common.vo.MsgFansMomentTaskFriendsVO;
import com.ibeeking.found.cop.service.mapper.CopEmployeeMapper;
import com.ibeeking.found.cop.service.mapper.MsgFansMomentTaskFriendsMapper;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.date.DateUtil;
import com.ibeeking.nematos.utils.json.JsonUtils;
import me.chanjar.weixin.cp.api.WxCpExternalContactService;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.external.WxCpGetMomentComments;
import me.chanjar.weixin.cp.bean.external.WxCpGetMomentSendResult;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName MsgFansMomentTaskFriendsServiceImpl
 * @Description
 * @Author ibeeking
 * @Date 2021-01-27 18:50
 **/
@Service
public class MsgFansMomentTaskFriendsServiceImpl extends ServiceImpl<MsgFansMomentTaskFriendsMapper, MsgFansMomentTaskFriendsDO> implements IMsgFansMomentTaskFriendsService {

    @Resource
    private MsgFansMomentTaskFriendsMapper msgFansMomentTaskFriendsMapper;

    @Resource
    private CopEmployeeMapper copEmployeeMapper;

    @Resource
    private IWxOpenService wxOpenServiceImpl;

    @Override
    public List<MsgFansMomentTaskFriendsVO> list(MsgFansMomentTaskFriendsQuery query) {
        List<MsgFansMomentTaskFriendsDO> entityDOS = msgFansMomentTaskFriendsMapper.selectList(new LambdaQueryWrapper<MsgFansMomentTaskFriendsDO>()
                .eq(query.getId() != null, MsgFansMomentTaskFriendsDO::getId, query.getId())
                .eq(StringUtils.isNotBlank(query.getMomentCode()), MsgFansMomentTaskFriendsDO::getMomentCode, query.getMomentCode())
                .eq(query.getMomentId() != null, MsgFansMomentTaskFriendsDO::getMomentId, query.getMomentId())
        );
        List<MsgFansMomentTaskFriendsVO> entityVOS =JsonUtils.jsonToList(entityDOS, MsgFansMomentTaskFriendsVO.class);
        return entityVOS;
    }

    @Override
    public MsgFansMomentTaskFriendsVO queryById(Long id) {
        MsgFansMomentTaskFriendsDO entityDO = msgFansMomentTaskFriendsMapper.selectById(id);
        if(entityDO == null) throw new BusinessException("没有查到相关记录！");
        MsgFansMomentTaskFriendsVO entityVO = BeanUtil.convertBean(entityDO, MsgFansMomentTaskFriendsVO.class);
        return entityVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean syncFansMomentTaskFriendsListFromWxCp(Integer tenantId, List<String> momentCodeList, Map<String, List<String>> senderCodeMap){
        if(Collections3.isNotEmpty(momentCodeList)) {
             WxCpService wxCpService = wxOpenServiceImpl.getWxCpService(tenantId.longValue());
            WxCpConfigStorage wxCpConfigStorage = wxCpService.getWxCpConfigStorage();
            if (wxCpConfigStorage == null) {
                throw new BusinessException("获取企微服务失败!");
            }

            WxCpExternalContactService wxCpExternalContactService = wxCpService.getExternalContactService();
            if (wxCpExternalContactService == null) throw new BusinessException("获取企微服务外部联系人服务!");
            List<CopEmployeeDO> copEmployeeDOS = copEmployeeMapper.selectList(new LambdaQueryWrapper<>());
            Map<String, Long> copEmployeeNameMaps = Collections3.isNotEmpty(copEmployeeDOS)?copEmployeeDOS.stream().collect(Collectors.toMap(CopEmployeeDO::getEmployeeCode, CopEmployeeDO::getId, (o, n) -> n)):null;
            List<MsgFansMomentTaskFriendsDO> allMsgFansMomentTaskFriendsDOS = new ArrayList<>();
            for (String momentCode : momentCodeList) {
                List<MsgFansMomentTaskFriendsDO> momentTaskFriendsDOS = msgFansMomentTaskFriendsMapper.selectList(new LambdaQueryWrapper<MsgFansMomentTaskFriendsDO>().eq(MsgFansMomentTaskFriendsDO::getMomentCode, momentCode));
                Map<String, MsgFansMomentTaskFriendsDO> momentTaskFriendsMap = Collections3.isNotEmpty(momentTaskFriendsDOS)?momentTaskFriendsDOS.stream().collect(Collectors.toMap(MsgFansMomentTaskFriendsDO::getFriendsCode, x->x, (o, n) -> n)):null;

                List<String> senderList = senderCodeMap!=null?senderCodeMap.get(momentCode):null;
                if(Collections3.isNotEmpty(senderList)) {
                    for(String senderCode:senderList) {
                        try {
                            WxCpGetMomentComments wxCpGetMomentComments = wxCpExternalContactService.getMomentComments(momentCode, senderCode);
                            LogUtils.info("====process wxCpGetMomentComments:{}====", JsonUtils.toJsonStr(wxCpGetMomentComments));
                            Map<String, WxCpGetMomentComments.CommentLikeItem> mommentItemMap = new HashMap<>();
                            Map<String, WxCpGetMomentComments.CommentLikeItem> likeItemMap = new HashMap<>();
                            if (wxCpGetMomentComments != null) {
                                List<WxCpGetMomentComments.CommentLikeItem>  mommentItemList= wxCpGetMomentComments.getCommentList();
                                if(Collections3.isNotEmpty(mommentItemList)){
                                    for(WxCpGetMomentComments.CommentLikeItem mommentItem: mommentItemList){
                                        String friendsCode = mommentItem.getExternalUserId();
                                        mommentItemMap.put(friendsCode,mommentItem);
                                    }
                                }
                                List<WxCpGetMomentComments.CommentLikeItem>  likeItemList= wxCpGetMomentComments.getLikeList();
                                if(Collections3.isNotEmpty(likeItemList)){
                                    for(WxCpGetMomentComments.CommentLikeItem likeItem: likeItemList){
                                        String friendsCode = likeItem.getExternalUserId();
                                        likeItemMap.put(friendsCode,likeItem);
                                    }
                                }
                            }
                            String nextCursor = null;
                            do {
                                WxCpGetMomentSendResult wxCpGetMomentSendResult = wxCpExternalContactService.getMomentSendResult(momentCode, senderCode,nextCursor, 4000);
                                LogUtils.info("====process wxCpGetMomentSendResult:{}====", JsonUtils.toJsonStr(wxCpGetMomentSendResult));
                                if(wxCpGetMomentSendResult!=null){
                                    nextCursor = wxCpGetMomentSendResult.getNextCursor();
                                    List<me.chanjar.weixin.cp.bean.external.moment.CustomerItem> customerItemList = wxCpGetMomentSendResult.getCustomerList();
                                    if(Collections3.isNotEmpty(customerItemList)){
                                        for(me.chanjar.weixin.cp.bean.external.moment.CustomerItem customerItem: customerItemList){
                                            String friendsCode = customerItem.getExternalUserId();
                                            String rtnSenderCode = customerItem.getUserId();
                                            if(StringUtils.isNotEmpty(friendsCode)){
                                                if(momentTaskFriendsMap!=null && momentTaskFriendsMap.containsKey(friendsCode)) {
                                                    MsgFansMomentTaskFriendsDO msgFansMomentTaskFriendsDO = momentTaskFriendsMap.get(friendsCode);
                                                    msgFansMomentTaskFriendsDO.setSenderCode(senderCode);
                                                    if(copEmployeeNameMaps!=null && copEmployeeNameMaps.containsKey(senderCode)) {
                                                        msgFansMomentTaskFriendsDO.setSenderId(copEmployeeNameMaps.get(senderCode));
                                                    }
                                                    if(mommentItemMap!=null && mommentItemMap.containsKey(friendsCode)) {
                                                        WxCpGetMomentComments.CommentLikeItem commentItem = mommentItemMap.get(friendsCode);
                                                        if(commentItem!=null) {
                                                            msgFansMomentTaskFriendsDO.setHaveComment(1);
                                                            Long createTimeLong = commentItem.getCreateTime();
                                                            if(createTimeLong!=null) {
                                                                msgFansMomentTaskFriendsDO.setCommentTime(DateUtil.longToLocalDateTime(createTimeLong));
                                                            }
                                                        }
                                                    }
                                                    if(likeItemMap!=null && likeItemMap.containsKey(friendsCode)) {
                                                        WxCpGetMomentComments.CommentLikeItem likeItem = likeItemMap.get(friendsCode);
                                                        if(likeItem!=null) {
                                                            msgFansMomentTaskFriendsDO.setHaveLike(1);
                                                            Long createTimeLong = likeItem.getCreateTime();
                                                            if(createTimeLong!=null) {
                                                                msgFansMomentTaskFriendsDO.setLikeTime(DateUtil.longToLocalDateTime(createTimeLong));
                                                            }
                                                        }
                                                    }
                                                    allMsgFansMomentTaskFriendsDOS.add(msgFansMomentTaskFriendsDO);
                                                }
                                            }
                                        }
                                    }
                                }else{
                                    nextCursor = null;
                                }
                            } while (nextCursor == null);
                        } catch (Exception e) {
                            LogUtils.error("获取客户朋友圈发表后的可见客户列表异常，原因：{}",e);
                            return false;
                        }
                    }
                }
            }
            LogUtils.info("====process allMsgFansMomentTaskFriendsDOS:{}====", JsonUtils.toJsonStr(allMsgFansMomentTaskFriendsDOS));
            if(Collections3.isNotEmpty(allMsgFansMomentTaskFriendsDOS)){
                super.updateBatchById(allMsgFansMomentTaskFriendsDOS);
            }
        }
        return true;
    }
}
